<template>
  <div>
    <el-upload
      :action="`${path}/files/upload`"
      :data="uploadData"
      :before-upload="checkFile"
      :headers="{ 'x-token': userStore.token }"
      :on-error="uploadError"
      :on-success="uploadSuccess"
      :on-remove="handleRemove"
      v-model:file-list="fileList"
      class="upload-demo"
      multiple
      drag
    >
    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
    <div class="el-upload__text">
      将文件拖到此处或<em>点击上传</em>
    </div>
    <template #tip>
      <div class="el-upload__tip">
        上传文件大小不能超过 5MB
      </div>
    </template>
    </el-upload>
  </div>
</template>

<script setup>

import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/pinia/modules/user'


defineOptions({
  name: 'UploadFile',
})

const props = defineProps({
  fileType: String,
  fileList: Array
    })

const uploadData =ref({
  "type":props.fileType
})


const fileList=  ref([])
const list=  []

const emit = defineEmits(['on-success'])

const path = ref(import.meta.env.VITE_BASE_API)

const userStore = useUserStore()
const fullscreenLoading = ref(false)

const checkFile = (file) => {
  fullscreenLoading.value = true
  const isLt5M = file.size / 1024 / 1024 < 5 // 5MB, @todo 应支持项目中设置
  let pass = true
  if (!isLt5M ) {
    ElMessage.error('上传文件大小不能超过 5MB')
    fullscreenLoading.value = false
    pass = false
  }
  console.log('upload file check result: ', pass)
  return pass
}

//定义一个
const uploadSuccess = (res) => {
  if (res) {
    if (res.code === 0){
      list.push({name:res.data.fileName,path:res.data.fileParh,ID:res.data.ID})
      emit('on-success', res.data)
    }else{
      ElMessage({
        type: 'error',
        message: res.data.msg ,
      })
    }
  }
}

const handleRemove  = (file) => {
  list.value=JSON.parse(JSON.stringify(fileList))
  const list1= list.value.filter((item) => {
          return !toRaw(file).response.data.ID.includes(item.ID)
    });

  console.log(list1)
}
const uploadError = () => {
  ElMessage({
    type: 'error',
    message: '上传失败'
  })
  fullscreenLoading.value = false
}

</script>
